//
//  HomeSearchVC.m
//  PensionUser
//
//  Created by 杨涛 on 2019/2/25.
//  Copyright © 2019 znz. All rights reserved.
//

#import "BenDiSearchVC.h"
#import "HistorySearchCell.h" // 历史记录cell
#import "SearchHistoryWordsView.h"
#import "SearchNavbarView.h"
#import "MailGoodsModel.h"
#import "BusinessModel.h"
#import "AbulkCell.h"
#import "MailCell.h"
#import "HomeCell.h"
#import "MailDetailsVC.h"
#import "BusinessDetailedVC.h"
#import "PagingViewController.h"
#import "SearchHomeDeleteView.h"


typedef void (^HistoryWordsBlock)(NSString *title);

@interface BenDiSearchVC () <UITextFieldDelegate>
{
    SearchNavbarView *_searchNavbarView;
    NSString *_keyStr;
}
@property (nonatomic, assign) BOOL isHistory;
@property (strong, nonatomic) NSMutableArray *historyArray;
// 历史搜索
@property (nonatomic, strong) SearchHistoryWordsView *historyWordsView;
@end

@implementation BenDiSearchVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self.view setBackgroundColor:VCBgcolor];
    
    _isHistory = YES;
    
    _keyStr = History;

    
    
    
    if ([ZNZDefaults objectForKey:_keyStr]) {
        self.historyArray = [NSMutableArray arrayWithArray:[ZNZDefaults objectForKey:_keyStr]];
    } else {
        self.historyArray = [NSMutableArray arrayWithCapacity:0];
    }
    
    [self createSearchView]; // 创建搜索框
    
    [self setupTableView]; // 创建tableview视图
    
    
    
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES];
    
    [self.baseTableview reloadData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO];
}

- (SearchHistoryWordsView *)historyWordsView
{
    if (!_historyWordsView) {
        _historyWordsView = [[NSBundle mainBundle] loadNibNamed:@"SearchHistoryWordsView" owner:self options:nil].lastObject;
        _historyWordsView.frame = CGRectMake( 0, _searchNavbarView.bottom, KSCREEN_WIDTH, KSCREEN_HEIGHT - _searchNavbarView.bottom);
        [_historyWordsView layoutIfNeeded];
        
        // 设置点击事件
        __weak typeof(self) wkSelf = self;
        _historyWordsView.historyWordsClick = ^(NSString * _Nonnull title) {
            NSLog(@"historyWordsClick title = %@", title);
            _searchNavbarView.tf.text = title;
            [wkSelf searchClick];
        };
    }
    return _historyWordsView;
}

#pragma mark - 创建搜索框
- (void)createSearchView {
    _searchNavbarView = [SearchNavbarView GetmyHeaderView];
    [_searchNavbarView setFrame:kFrame( 0, 0, KSCREEN_WIDTH, NEW_NavHeight)];
    [_searchNavbarView.tf setDelegate:self];
    [_searchNavbarView.tf addTarget:self action:@selector(textFieldChanged:) forControlEvents:UIControlEventEditingChanged];
    [_searchNavbarView.searchBtn addTarget:self action:@selector(searchClick) forControlEvents:UIControlEventTouchUpInside];
    [_searchNavbarView.searchBtn2 addTarget:self action:@selector(searchClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_searchNavbarView];
}


#pragma mark - 创建tableview视图
- (void)setupTableView {
    self.tableViewFrame = CGRectMake( 0, _searchNavbarView.bottom, KSCREEN_WIDTH, KSCREEN_HEIGHT - _searchNavbarView.bottom);
    self.tableviewStyle = UITableViewStylePlain;
    self.baseTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.baseTableview registerNib:[UINib nibWithNibName:@"MailCell" bundle:nil] forCellReuseIdentifier:@"MailCell"];
    [self.baseTableview registerNib:[UINib nibWithNibName:@"AbulkCell" bundle:nil] forCellReuseIdentifier:@"AbulkCell"];
    [self.baseTableview registerNib:[UINib nibWithNibName:@"HomeCell" bundle:nil] forCellReuseIdentifier:@"HomeCell"];

    UIView *tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KSCREEN_WIDTH, 10)];
    [tableHeaderView setBackgroundColor:VCBgcolor];
    self.baseTableview.tableHeaderView = tableHeaderView;
    
    [self.baseTableview setBackgroundColor:VCBgcolor];
}

#pragma mark--------------------设置代理
#pragma mark - 返回标题文字
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *text = @"没有找到，重新搜索试试吧~";
    NSDictionary *attribute = @{NSFontAttributeName: kPLFont(14), NSForegroundColorAttributeName: BlackColor2};
    return [[NSAttributedString alloc] initWithString:text attributes:attribute];
}

#pragma mark - 是否允许滚动，默认NO
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark -  返回图片
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamed:@"meisousuo"];
}

#pragma mark -- tableview datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_isHistory) {
        if (_historyArray.count) {
            return self.historyArray.count;
        } else {
            return 0;
        }
    }
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_isHistory) {
      
        HistorySearchCell *cell = [HistorySearchCell cellWithTableView:tableView];
        
        [cell setBackgroundColor:[UIColor whiteColor]];
        
        if (self.historyArray.count > 0) {
            cell.titleLabel.text = [self.historyArray objectAtIndex:indexPath.row];
            cell.deleteBtn.hidden = YES;
            [cell.deleteBtn setTag:indexPath.row];
            [cell.deleteBtn addTarget:self action:@selector(removeFromHistoryWithTag:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        tableView.rowHeight = 56;
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
          
    } else {
        HomeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HomeCell"];
        cell.model = self.dataSource[indexPath.row];
        cell.discountBtn.hidden= YES;
        tableView.rowHeight = 135;
        return cell;
    }
    
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    SearchHomeDeleteView *headerView = [[NSBundle mainBundle] loadNibNamed:@"SearchHomeDeleteView" owner:self options:nil].lastObject;
    [headerView setBackgroundColor:kColor(245)];
    [headerView.deleteBtn addTarget:self action:@selector(deleteHistoryData) forControlEvents:UIControlEventTouchUpInside];
    
    if (_isHistory) {

        return headerView;
    }
       
    return nil;
}

- (void)deleteHistoryData {
    
    UIAlertController *alterController = [UIAlertController alertControllerWithTitle:nil message:@"是否清除历史记录？" preferredStyle:UIAlertControllerStyleAlert];
    
    [alterController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    
    [alterController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        _isHistory = YES;
        [self.historyArray removeAllObjects];
        [ZNZDefaults setObject:nil forKey:_keyStr];
        [self.baseTableview reloadData];
        
    }]];
    
    [self presentViewController:alterController animated:YES completion:nil];
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (_isHistory) {
        return 50.0f;
    }
    return 0.000001;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_isHistory) {
        _isHistory = NO;

        _searchNavbarView.tf.text = self.historyArray[indexPath.row];
        self.pageNum = 1;
        
        [self setMJRefresh];
        [self requestBussion];
        
    } else {
        
       
       BusinessDetailedVC *vc = [[BusinessDetailedVC alloc] init];
       vc.model = self.dataSource[indexPath.row];

       [self.navigationController pushViewController:vc animated:YES];
        
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self searchClick]; // 搜索事件
    return YES;
}
// 文字改变时调用
- (void)textFieldChanged:(UITextField*)textField {
    if ([CommonTTool isBlankString:textField.text]) {
        self.historyWordsView.hidden = NO;
    }
}

#pragma mark - 搜索事件
- (void)searchClick {
    [CommonTTool dismisKeyBoard];
    self.historyWordsView.hidden = YES;

    if (_searchNavbarView.tf.text.length == 0) {
        _isHistory = YES;
    } else {
        _isHistory = NO;
        if (![self.historyArray containsObject:_searchNavbarView.tf.text]) {
            [self.historyArray addObject:_searchNavbarView.tf.text];

            if (self.historyArray.count == 6) {
                [self.historyArray removeObjectAtIndex:0];
            }
            [ZNZDefaults setObject:self.historyArray forKey:_keyStr];
            self.historyWordsView.historyArray = self.historyArray;
        }
    }
    
    [self requestBussion];
}

#pragma mark - 删除某一个历史记录
- (void)removeFromHistoryWithTag:(UIButton*)sender {
    if (self.historyArray.count > 1) {
        [self.historyArray removeObjectAtIndex:sender.tag];
        [ZNZDefaults setObject:self.historyArray forKey:_keyStr];
        
    } else {  /** 全部删除 */
        [self.historyArray removeObjectAtIndex:sender.tag];
            [ZNZDefaults setObject:nil forKey:_keyStr];
        }
        [self.baseTableview reloadData];
}

#pragma mark - 设置刷新
- (void)setMJRefresh {
    self.baseTableview.mj_header = [ MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requrstNewData)];
    
    self.baseTableview.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestMoreData)];
}

- (void)requrstNewData {
    self.pageNum = 1;
    
    [self requestBussion];
    

    
}

- (void)requestMoreData {
    self.pageNum ++;
    
    [self requestBussion];
}




#pragma mark - 请求商家
- (void)requestBussion {

    
    [self.baseTableview.mj_header endRefreshing];
    [self.baseTableview.mj_footer endRefreshing];
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:@(self.pageNum) forKey:@"page"];
    [para setObject:_searchNavbarView.tf.text forKey:@"business_name"];
    [para setObject:@(10) forKey:@"limit"];
    [para setObject:@(2) forKey:@"is_hot"];
    [NetRequestTool postUrl:@"business/queryBusinessList" parameters:para success:^(id responseObject) {
       
       if (self.pageNum == 1) {
           
           [self.dataSource removeAllObjects];
           [self.dataSource addObjectsFromArray:[BusinessModel mj_objectArrayWithKeyValuesArray:responseObject[@"object"]]];
       } else {
           
           [self.dataSource addObjectsFromArray:[BusinessModel mj_objectArrayWithKeyValuesArray:responseObject[@"object"]]];
           if (![CommonTTool isStrNull:responseObject[@"page"]]) {
               NSArray *dicArr = responseObject[@"object"];
               if ([responseObject[@"page"][@"total_page"] integerValue] == self.pageNum || [responseObject[@"page"][@"total_page"] integerValue] == 1 || [responseObject[@"page"][@"total_page"] integerValue] == 0 || dicArr.count < 10) {
                   [self.baseTableview.mj_footer endRefreshingWithNoMoreData];
               }
           } else {
               [self.baseTableview.mj_footer endRefreshingWithNoMoreData];
           }
       }
       
       dispatch_async(dispatch_get_main_queue(), ^{
           [self.baseTableview reloadData];
       });
    } failure:^(NSInteger statusCode) {
       
    } finish:^{
       
    }];
   
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
